<template>
  <el-upload
    class="uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="customRequestFn"
  >
  </el-upload>
</template>

<script>
// 导入 cos 模块
import { mapGetters } from 'vuex'

const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDQhw9c6RZWUJvNgrpZDlCZpztlVBjAacf',
  SecretKey: '5KVo4FJDzc6RhpoeNzSmgWI0eAX6XwFP'
})

export default {
  name: 'uploadImg',
  props: {
    uploadSuccessFn: {
      type: Function
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  data () {
    return {
      imageName: '' // 上传成功的图片名称
    }
  },
  methods: {
    // 文件上传成功到后台 -> 回调函数
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 文件上传之前 -> 回调函数
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // upload 自定义上传过程
    customRequestFn (res) {
      if (res.file) {
        const name = Date.now() + this.userInfo.id + res.file.name
        cos.putObject(
          {
            Bucket: 'qjtwork-1314843671', // 存储桶的名称，必须
            Region: 'ap-guangzhou', // 存储桶所在地域，必须字段
            Key: name, // 文件名，必须
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: res.file // 上传文件对象
          },
          (err, data) => {
            if (err === null && data.statusCode === 200) {
              this.imageName = name
              this.$emit(
                'uploadSuccessFn',
                'https:qjtwork-1314843671.cos.ap-guangzhou.myqcloud.com/' + name
              )
            } else {
              this.$message.error(err)
            }
          }
        )
      }
    }
  }
}
</script>

<style>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
